﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Business;
using System.Data.SqlClient;
using System.Web.Configuration;
using Models;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Collections;
using iTextSharp.text.xml;
using iTextSharp.text.html;
using DataAccess;


public partial class client_Welcome : @base {
    string reportdate1 = "";
    string reportdate2 = "";
    string reportlink = "";
    int count = 0;
    private ReportServices rs = new ReportServices();
    OilReportService or = new OilReportService();
    PdfWriter writer;
    List<string> sourses = new List<string>();


    protected void Page_Load(object sender, EventArgs e) {
        string username = (string)Session["username"];
        int clientid = this.getclientid(username);


        DataTable clientlist = new DataTable();
        clientlist = rs.getChildrenClientByClientID(ClientDetails.ClientID);
        DataTable linkButtonInfo = new DataTable();
        linkButtonInfo.Columns.Add("Client_id", typeof(int));
        linkButtonInfo.Columns.Add("LatestDate", typeof(string));

        if ((clientlist == null) || clientlist.Rows.Count == 0) {

            DataTable ldate = new DataTable();
            ldate = or.getLatestdate(ClientDetails.ClientID);
            string latestdate = ldate.Rows[0][0].ToString();
            DataRow tableRow = linkButtonInfo.NewRow();
            tableRow["Client_id"] = ClientDetails.ClientID;
            tableRow["LatestDate"] = latestdate;
            linkButtonInfo.Rows.Add(tableRow);
            LinkButton lb = new LinkButton();
            lb.ID = "0";
            lb.Text = "New report of " + ClientDetails.ClientName + " on " + latestdate;
            lb.Click += new System.EventHandler(this.FullReport_Button_Click);
            Panel1.Controls.Add(lb);
        } else {
            int index = 0;

            foreach (DataRow r in clientlist.Rows) {
                int ChildClient = ToInt(r[0].ToString());
                string ChildName = r[1].ToString();
                DataTable ldate = new DataTable();
                ldate = rs.getLatestDateByClientID(ChildClient);
                if (ldate == null)
                    continue;
                string latestdate = ldate.Rows[0][0].ToString();
                DataRow tableRow1 = linkButtonInfo.NewRow();
                tableRow1["Client_id"] = ChildClient;
                tableRow1["LatestDate"] = latestdate;
                linkButtonInfo.Rows.Add(tableRow1);
                LinkButton linkbutton = new LinkButton();
                linkbutton.ID = "" + index;
                linkbutton.Text = "New report of " + ChildName + " on " + latestdate;
                linkbutton.Click += new System.EventHandler(this.FullReport_Button_Click);
                Panel1.Controls.Add(new LiteralControl("<br>"));
                Panel1.Controls.Add(linkbutton);
                index++;

            }
        }
        Session["linkButtonInfo"] = linkButtonInfo;










        //string subquery = "SELECT client_id FROM　Clients c "
        //    +"WHERE parent_client_id='"+clientid+"'";
        //CreateConn objcon = new CreateConn();
        //try
        //{
        //   DataTable dt =  objcon.SQLConnDataTable(subquery);
        //   if (dt != null && dt.Rows.Count > 0)
        //   {
        //       foreach (DataRow dr in dt.Rows)
        //       {
        //           int clientID = Int32.Parse((String)dr["client_id"]);
        //           initial(clientID);
        //       }
        //   }
        //   else
        //   {
        //       initial(clientid);
        //   }
        //}catch(Exception e1){
        //    Response.Write(e1.Message);

        //}

    }
    protected DataTable getSelectedSites(int selectedClient_id) {
        //selectedClient_id= 
        DataTable selectedSites = new DataTable();
        selectedSites.Columns.Add("siteName", typeof(string));
        selectedSites.Columns.Add("site_id", typeof(int));
        ReportServices rs = new ReportServices();
        selectedSites = rs.getSiteByCLientID(selectedClient_id);
        return selectedSites;
    }
    protected DataTable getSelectedStatus() {
        DataTable selectedStatus = new DataTable();
        selectedStatus.Columns.Add("statusName", typeof(string));
        selectedStatus.Columns.Add("status_id", typeof(int));
        OilReportService os = new OilReportService();
        selectedStatus = os.getExceptionSeverity();
        return selectedStatus;
    }
    protected Font getFont(BaseColor color, float size, string type) {
        Font font = new Font();
        font.Color = color;//BaseColor.BLUE;
        font.Size = size;// 6f;
        font.SetFamily(type);//"Arial");
        return font;
    }
    protected BaseColor getColor(int status_id) {
        switch (status_id) {
            case 1: return BaseColor.GREEN;
            case 2: return BaseColor.YELLOW;
            case 3: return BaseColor.ORANGE;
            case 4: return BaseColor.RED;
            case 5: return BaseColor.BLUE;
            default: return BaseColor.BLACK;
        };


    }
    protected PdfPTable setLegendTable(float width) {
        ReportServices report = new ReportServices();
        PdfPTable legendTable = new PdfPTable(2);
        // legendTable.TotalWidth = width+30;
        legendTable.SetTotalWidth(new float[] { 25, 170 });
        legendTable.WidthPercentage = 90;
        DataTable statusTable = new DataTable();
        statusTable = report.getSeverity();
        Phrase title = new Phrase("");
        PdfPCell c = new PdfPCell(title);
        c.Border = Rectangle.NO_BORDER;
        legendTable.AddCell(c);
        title = new Phrase("LEGEND", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12));
        c = new PdfPCell(title);
        c.Border = Rectangle.NO_BORDER;
        legendTable.AddCell(c);
        foreach (DataRow r in statusTable.Rows) {
            string statusName = r["statusName"].ToString();
            string statusDes = r["statusDescription"].ToString();
            int status_id = ToInt(r["status_id"].ToString());
            Phrase p1 = new Phrase(statusName, getFont(getColor(status_id), 8, "Arial"));
            PdfPCell fc = new PdfPCell(p1);
            fc.HorizontalAlignment = Element.ALIGN_LEFT;

            fc.Border = Rectangle.NO_BORDER;
            fc.VerticalAlignment = Element.ALIGN_LEFT;
            legendTable.AddCell(fc);
            p1 = new Phrase(statusDes, getFont(BaseColor.BLACK, 8, "Arial"));
            fc = new PdfPCell(p1);
            fc.HorizontalAlignment = Element.ALIGN_LEFT;
            fc.Border = Rectangle.NO_BORDER;
            fc.VerticalAlignment = Element.ALIGN_LEFT;
            legendTable.AddCell(fc);
        }

        return legendTable;
    }
    protected PdfPTable setTitleTable(ArrayList title, float width) {
        PdfPTable titleTable = new PdfPTable(1);
        //titleTable.SetTotalWidth(new float[] {5 });
        titleTable.WidthPercentage = 82;

        Chunk ck;


        Font font1; Phrase p1 = new Phrase();
        // titleTable.TotalWidth = width-80;
        for (int i = 0; i < title.Count; i++) {
            if (i + 1 == title.Count)
                font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 13);
            else
                font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 15);
            ck = new Chunk(title[i].ToString(), font1);


            p1.Add(ck);
            p1.Add(Chunk.NEWLINE);
            p1.Add(Chunk.NEWLINE);
        }
        PdfPCell fc = new PdfPCell(p1);
        fc.HorizontalAlignment = Element.ALIGN_CENTER;
        fc.VerticalAlignment = Element.ALIGN_MIDDLE;
        fc.MinimumHeight = 0f;
        fc.Border = Rectangle.NO_BORDER;
        fc.VerticalAlignment = Element.ALIGN_LEFT;
        fc.MinimumHeight = 0;
        fc.PaddingBottom = 0.1f;
        fc.PaddingTop = 0.1f;
        //fc.Leading=15f;
        titleTable.AddCell(fc);


        return titleTable;
    }
    protected string getSitesTitle(DataTable sites) {
        string sitesTitle = "";
        int num = sites.Rows.Count;
        int i = 0;

        foreach (DataRow s in sites.Rows) {
            sitesTitle = sitesTitle + s["siteName"].ToString();
            i++;
            if (i + 1 == num)
                sitesTitle = sitesTitle + " & ";
            else

                if (i != num)
                    sitesTitle = sitesTitle + ", ";

        }
        return sitesTitle;
    }

    protected PdfPTable setTableInfo(ArrayList info, float width) {
        PdfPTable tableInfo = new PdfPTable(2);
        Chunk ck;


        iTextSharp.text.Font font1;
        tableInfo.TotalWidth = width;
        for (int i = 0; i < 16; i++) {
            Phrase p1 = new Phrase();
            switch (i) {
                case 0:
                case 2:
                case 4:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12);
                    ck = new Chunk(info[i].ToString(), font1);
                    p1.Add(ck);
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
                case 1:
                case 3:
                case 5:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 11);
                    ck = new Chunk(info[i].ToString(), font1);
                    p1.Add(ck);
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
                case 13:
                case 15:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 10.5f);
                    String address = info[i].ToString();
                    String t;
                    int index = 0;
                    int count = 0;
                    while (true) {
                        count = address.IndexOf(';', index);
                        if (count == -1) {
                            ck = new Chunk(address.Substring(index).Trim(), font1);
                            p1.Add(ck);
                            break;
                        }
                        t = address.Substring(index, count - index).Trim();
                        index = count + 1;
                        ck = new Chunk(t, font1);
                        p1.Add(ck);
                        p1.Add(Chunk.NEWLINE);

                    }
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
                case 12:
                case 14:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 10);
                    ck = new Chunk(info[i].ToString(), font1);
                    p1.Add(ck);
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
                default:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 9.5f);
                    ck = new Chunk(info[i].ToString(), font1);
                    p1.Add(ck);
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
            }
            PdfPCell fc = new PdfPCell(p1);
            fc.HorizontalAlignment = Element.ALIGN_LEFT;
            fc.MinimumHeight = 0f;
            fc.Border = Rectangle.NO_BORDER;
            fc.VerticalAlignment = Element.ALIGN_LEFT;
            if ((i > 5) && (i < 10)) {
                // fc.SetLeading(0, 1.0f);
                fc.FixedHeight = 13;

            } else
                fc.MinimumHeight = 0;
            fc.PaddingBottom = 0.1f;
            fc.PaddingTop = 0.1f;
            tableInfo.AddCell(fc);
        }
        return tableInfo;

    }
    protected void FullReport_Button_Click(object sender, EventArgs e) {
        //TextBox1.Text = "get report";
        ArrayList title = new ArrayList(3);
        ArrayList infor = new ArrayList(16);
        Paragraph pa;

        string selectedDate = "";
        Document document = new Document(PageSize.A4, 120, 85, 83, 125);
        headerfooter hf = new headerfooter();
        UserServices us = new UserServices();
        DataTable selectedSites = new DataTable();
        DataTable selectedStatus = new DataTable();
        selectedSites.Columns.Add("siteName", typeof(string));
        selectedSites.Columns.Add("site_id", typeof(int));
        selectedStatus.Columns.Add("statusName", typeof(string));
        selectedStatus.Columns.Add("status_id", typeof(int));

        int selectedClient_id = 0;
        Client selectedClient = new Client();
        string ClientParentName = "";

        LinkButton l = (LinkButton)sender;
        DataTable linkButtonInfo = (DataTable)Session["linkButtonInfo"];
        int indx = ToInt(l.ID);
        selectedClient_id = ToInt(linkButtonInfo.Rows[indx][0].ToString());

        string dateIndex = "0";
        // System.DateTime str_date = new DateTime();
        selectedClient = us.getClientByID(selectedClient_id);

        string selectedClientName = selectedClient.ClientName;


        string date = linkButtonInfo.Rows[indx][1].ToString();
        selectedDate = date;
        dateIndex = date.Replace('/', '-');



        //try {
        //    selectedDate = DropDownListDate.SelectedValue;
        //    dateIndex = DropDownListDate.SelectedIndex + 1;
        //} catch (Exception ex) {
        //    Console.Write(ex);
        //    // MessageBox.Show("No report available");

        //}

        // step 2: we create a writer that listens to the document
        String path1 = Server.MapPath("Report");
        String p = Server.MapPath("Images");

        String path = path1 + "/Template.pdf";


        int ok = 0;
        while (ok != -1) {

            try {

                writer = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));
                ok = -1;
            } catch (Exception) {
                ok++;
                path = path1 + "/Template" + ok.ToString() + ".pdf";
            }
        }


        Rectangle page = document.PageSize;
        // document.SetMargins(120, 90, 83, 30);
        document.SetMargins(120, 20, 83, 125);

        hf.setHeader(p + "/logoi2i.png", page.Width + 35, Element.ALIGN_CENTER, Rectangle.NO_BORDER, 75);
        hf.setFooter(page.Width);

        PdfPTable head = hf.Head;
        PdfPTable foot = hf.Foot;

        try {

            selectedSites = getSelectedSites(selectedClient_id);

            selectedStatus = getSelectedStatus();
            document.Open();

            // Add header for first page
            head.WriteSelectedRows(0, -1, 0, 820, writer.DirectContent);
            foot.WriteSelectedRows(0, -1, 0, 80, writer.DirectContent);
            string tt = "";
            if (ClientDetails.ParentClientID != 0) {
                ClientParentName = "" + us.getClientByID(ClientDetails.ParentClientID).ClientName;
                //} else
                //    ClientParentName = ClientDetails.ClientName;


                //title.Add(ClientParentName + " (" + selectedClientName + ")"); // + " Sites";
                tt = ClientParentName + " (" + selectedClientName + ")";
            } else
                //ClientParentName = ClientDetails.ClientName;
                tt = selectedClientName;
            //title.Add(ClientParentName + " (" + selectedClientName + ")"); // + " Sites";
            title.Add(tt);

            string sitesTitle = getSitesTitle(selectedSites);

            //  title.Add(sitesTitle);
            title.Add("Oil Inspection and Survey Report");
            title.Add(selectedDate);
            PdfPTable TitleTable = new PdfPTable(1);
            TitleTable = setTitleTable(title, page.Width);


            for (int i = 0; i < 2; i++) {
                Phrase t = new Phrase("");
                pa = new Paragraph(t);
                if (i == 0)
                    pa.Leading = 110;
                else
                    pa.Leading = 20;
                pa.Alignment = Element.ALIGN_CENTER;
                document.Add(pa);


            }
            TitleTable.HorizontalAlignment = Element.ALIGN_LEFT;
            document.Add(Chunk.NEWLINE);
            document.Add(Chunk.NEWLINE);
            document.Add(TitleTable);
            string fileName = "" + selectedClient.ClientID + "-VA-" + getShortName(selectedClient.ClientName) + "-" + dateIndex + ".pdf";
            PdfPTable information = new PdfPTable(2);
            infor.Add("Engineer");
            infor.Add("Paul Clibbon");
            infor.Add("Report Filename");
            infor.Add(fileName);
            infor.Add("Report Distribution");
            infor.Add(selectedClient.ContactPerson);
            infor.Add("Phone");
            infor.Add(selectedClient.PhoneMobile.ToString());
            infor.Add("Fax");
            infor.Add(selectedClient.Fax.ToString());
            infor.Add("Email");
            infor.Add(selectedClient.Email);
            infor.Add("Address");
            infor.Add(selectedClient.Address);
            infor.Add("Report Distribution: Email reports in PDF format to:  ");
            infor.Add(selectedClient.DistributedEmail);
            information = setTableInfo(infor, page.Width - 80);
            information.HorizontalAlignment = Element.ALIGN_CENTER;
            document.Add(Chunk.NEWLINE);
            document.Add(Chunk.NEWLINE);
            document.Add(information);

            document.Add(Chunk.NEWLINE);
            document.Add(Chunk.NEWLINE);
            PdfPTable legend = new PdfPTable(2);
            legend = setLegendTable(page.Width);
            legend.HorizontalAlignment = Element.ALIGN_LEFT;
            document.Add(legend);

            document.Close();

            DataTable MachinesOfSites = new DataTable();
            ReportServices r = new ReportServices();
            // MachinesOfSites = r.getMachineOfSites(selectedSites);
            DataTable componentsOfSites = new DataTable();
            componentsOfSites = or.getComponentsBySitesAndStatusByDate(selectedSites, selectedStatus, selectedDate);// str_date);

            int num = componentsOfSites.Rows.Count;
            //TextBox1.Text = TextBox1.Text + "/num:" + num;
            int index = 0;
            int sourseIndex = 0;

            string test = Server.MapPath("inbox");
            // string oilPath = Server.MapPath("inbox") + "/";
            string oilPath = test.Replace("client\\inbox", "Mails") + "/";

            sourses.Add(path);
            test = test + path;
            foreach (DataRow site in selectedSites.Rows) {
                String siteName = site["siteName"].ToString();
                string siteID = site["site_id"].ToString();

                index++;
                //int count = 0;
                DataRow[] componentsOfSite = componentsOfSites.Select("site_id =  " + siteID.Trim());
                foreach (DataRow co in componentsOfSite) {
                    string nameLink = co["reportlink"].ToString();

                    string sourse = oilPath + nameLink;


                    sourses.Add(sourse);
                    //TextBox1.Text = TextBox1.Text + "/" + sourse;
                    sourseIndex++;
                }


            }
            PdfMerge merg = new PdfMerge();

            string file = merg.MergeFiles(oilPath, sourses);



            // set name for attact file


            Response.Clear();
            Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
            Response.ContentType = "application/pdf";
            Response.WriteFile(file);
            Response.Flush();
            Response.End();
            Response.Clear();

        } catch (Exception ee) {
            Console.Error.WriteLine(ee.StackTrace);
            Console.Error.WriteLine(ee.Message);
            if (ee.InnerException != ee) {
                //TextBox1.Text = TextBox1.Text + "hong roi";// +ee.InnerException.Message.ToString();
                ////Console.Error.WriteLine(ee.InnerException.Message);
            }
        }



        // End of Thao



    }


    protected int getclientid(String username) {
        string query = "select client_id FROM Users u "
            + "where username='" + username + "'";
        CreateConn objcon = new CreateConn();
        try {
            DataTable dt = objcon.SQLConnDataTable(query);
            if (dt.Rows.Count > 0) {
                foreach (DataRow dr in dt.Rows) {
                    int id = Int32.Parse(dr["client_id"].ToString());
                    return id;
                }
            }
        } catch (Exception e1) {
            Response.Write(e1.Message);
        }
        return 0;
    }
    private void initial(int clientid) {
        string query = "SELECT c.clientName, s.siteName, m.machineName, comp.componentName, op.tested_date, op.reportlink, op.status"
+ " FROM            Clients AS c INNER JOIN "
                         + "Sites AS s ON c.client_id = s.client_id INNER JOIN "
                         + "Machines AS m ON s.site_id = m.site_id INNER JOIN "
                         + "Components AS comp ON m.machine_id = comp.machine_id INNER JOIN "
                         + "OilReports AS op ON comp.component_id = op.Component_id WHERE c.client_id='" + clientid + "'"
+ " ORDER BY op.tested_date DESC";
        CreateConn objcon = new CreateConn();
        try {
            DataTable dt = objcon.SQLConnDataTable(query);
            foreach (DataRow dr in dt.Rows) {
                String tested_date = dr["tested_date"].ToString();
                reportlink = dr["reportlink"].ToString();
                string status = dr["status"].ToString();
                string clientname = dr["clientName"].ToString();
                HyperLink hl_1 = new HyperLink();
                hl_1.Target = "_blank";
                hl_1.NavigateUrl = "../inbox/" + reportlink;
                hl_1.Text = "new oil report of '" + clientname + "' on " + tested_date + " " + status + '\n';

                Panel1.Controls.Add(hl_1);
                Panel1.Controls.Add(new LiteralControl("<BR>"));

            }
        } catch (Exception e3) {
            Response.Write(e3.Message);
        }
    }
    protected string IntToString(string i) {
        string sta = "";
        switch (i) {
            case "1": sta = "Normal"; break;
            case "2": sta = "Abnormal"; break;
            case "3": sta = "Moderate"; break;
            case "4": sta = "Severe"; break;
        }
        return sta;

    }

    protected string getShortName(string name) {
        string name1 = name.Trim();
        //int length = name.Length;
        string shorname = "";
        int ix = 0;
        shorname = shorname + name.Substring(0, 1).ToString().ToUpper();
        name1 = name.Substring(1);
        int index = index = name1.IndexOf(" ", ix);
        while (index != -1) {

            name1 = name1.Substring(index).Trim();
            shorname = shorname + name1.Substring(0, 1);
            index = name1.IndexOf(" ", ix);
        }
        return shorname;
    }

    public void getreportinfor() {

    }
    private class headerfooter {
        private PdfPTable head;
        private PdfPTable foot;
        private iTextSharp.text.Image _img;
        private Font font;
        private String t1 = "i2iTechnologies PO Box 1192, Clevand Qld 4163, Australia";
        private String t2 = "Office (07) 3829 1235 Fax (07) 3829 1238 Mob: 0439 717 244 Web: www.i2i-technologies.com.au ";
        private String t3 = "@i2iTechnologies";

        public headerfooter() {
            head = new PdfPTable(1);
            foot = new PdfPTable(1);
            font = new Font();
            font.Color = BaseColor.BLUE;
            font.Size = 6f;
            font.SetFamily("Arial");
        }
        public PdfPTable Head {
            get { return head; }

        }
        public PdfPTable Foot {
            get { return foot; }

        }

        public void setHeader(String path, float width, int align, int border, int scale) {
            PdfPTable header = new PdfPTable(1);
            header.TotalWidth = width - 35;
            _img = iTextSharp.text.Image.GetInstance(path);
            _img.ScalePercent(scale);
            PdfPCell c = new PdfPCell(_img, false);

            c.HorizontalAlignment = align;
            c.Border = border;
            header.AddCell(c);
            head = header;

        }
        public void setFooter(float width) {

            PdfPTable footer = new PdfPTable(1);
            footer.TotalWidth = width;
            Chunk ck = new Chunk(t1, font);
            Phrase p1 = new Phrase(ck);

            PdfPCell fc = new PdfPCell(p1);
            fc.HorizontalAlignment = Element.ALIGN_CENTER;
            fc.Border = Rectangle.NO_BORDER;
            fc.VerticalAlignment = Element.ALIGN_MIDDLE;

            fc.Rowspan = 1;
            footer.AddCell(fc);

            ck = new Chunk(t2, font);
            fc.Phrase = new Phrase(ck);
            fc.Rowspan = 1;
            footer.AddCell(fc);

            fc.Rowspan = 1;

            ck = new Chunk(t3, font);
            fc.Phrase = new Phrase(ck);
            footer.AddCell(fc);

            foot = footer;

        }
    }

}
